package com.leancloud.circle.activity;

import android.Manifest;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.aries.ui.view.title.TitleBarView;
import com.leancloud.circle.R;
import com.leancloud.circle.api.CircleApiConstant;
import com.leancloud.circle.entity.UploadInfo;
import com.vise.xsnow.http.ViseHttp;
import com.vise.xsnow.http.callback.ACallback;
import com.vise.xsnow.http.request.PostRequest;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import cn.bingoogolapple.photopicker.widget.BGASortableNinePhotoLayout;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;
import tech.com.commoncore.Config;
import tech.com.commoncore.base.BaseTitleActivity;
import tech.com.commoncore.basecomponent.ServiceFactory;
import tech.com.commoncore.constant.ApiConstant;
import tech.com.commoncore.entity.BaseTResp;
import tech.com.commoncore.utils.FileUtils;
import tech.com.commoncore.widget.photoPicker.MyPhotoPickerActivity;
import tech.com.commoncore.widget.photoPicker.MyPhotoPickerPreviewActivity;

@Route(path = "/topic/post")
public class PostTopicActivity extends BaseTitleActivity implements EasyPermissions.PermissionCallbacks, BGASortableNinePhotoLayout.Delegate {

    private EditText mEtContent;
    private EditText mEtTitle;
    private BGASortableNinePhotoLayout mPhotoLayout;

    private static final int PRC_PHOTO_PICKER = 1;

    private static final int RC_CHOOSE_PHOTO = 1;
    private static final int RC_PHOTO_PREVIEW = 2;

    @Override
    public void setTitleBar(TitleBarView titleBar) {
        titleBar.setTitleMainText(R.string.circle_post).setStatusBarLightMode(false).setLeftTextDrawable(R.mipmap.back_white).setTitleMainTextColor(Color.WHITE).setRightTextColor(Color.WHITE)
                .setRightText(R.string.circle_post_right).setOnRightTextClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                submit();
            }
        });
    }

    private void submit() {

        String title = mEtTitle.getText().toString().trim();
        String content = mEtContent.getText().toString().trim();
        if (TextUtils.isEmpty(title)) {
//            ToastUtil.show(R.string.circle_title_hint+"...");
            Toast.makeText(mContext, R.string.circle_title_hint, Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(content)) {
            Toast.makeText(mContext,R.string.circle_content_hint, Toast.LENGTH_SHORT).show();
            return;
        }

        //图片列表
        List<String> picList = mPhotoLayout.getData();
//        showLoading("uploading...");
        showLoading(getResources().getString(R.string.circle_postting)+"...");

        if (picList.size() == 0) {
            //没图片
//            send(content, new ArrayList<String>());
            send(title,content, new ArrayList<String>());
        } else {
            //有图片
            uploadPic(title,content, picList);
//            uploadPic(content, picList);
        }
    }

    @Override
    public int getContentLayout() {
        return R.layout.circle_activity_post_topic;
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        mEtTitle = findViewById(R.id.et_title);
        mEtContent = findViewById(R.id.et_content);
        mPhotoLayout = findViewById(R.id.photoLayout);

        // 设置拖拽排序控件的代理
        mPhotoLayout.setDelegate(this);

    }

    //发布
    private void send(String title,String content, List<String> imgList) {

        PostRequest request = ViseHttp.POST(CircleApiConstant.ADD_CIRCLE)
                .baseUrl(ApiConstant.BASE_URL)
                .addHeader("XX-Token", ServiceFactory.getInstance().getLoginService().getCurrentUser().getToken())
                .addHeader("XX-Device-Type", "android")
                .addParam("post_title", title)
                .addParam("post_keywords", "")
                .addParam("post_excerpt", "")
                .addParam("post_source", "")
                .addParam("post_content", content)
                .addParam("category", CircleApiConstant.TOPIC_ID + "");

        String more = "";
        if (imgList.size() > 0) {
            for (int i = 0; i < imgList.size(); i++) {
                if (i == 0) {
                    more = more + CircleApiConstant.HEAD_URL + imgList.get(i);
                } else {
                    more = more + "," + CircleApiConstant.HEAD_URL + imgList.get(i);
                }
            }
        }
        request.addParam("more", more);

        request.request(new ACallback<BaseTResp<String>>() {

            @Override
            public void onSuccess(BaseTResp<String> data) {
                if ((1 == data.code)) {
                    Toast.makeText(mContext,R.string.circle_posted, Toast.LENGTH_SHORT).show();
//                    BusManager.getBus().post(new RefreshCircleListEvent());
                    finish();
                } else {
                    Toast.makeText(mContext,R.string.circle_posted_fail, Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFail(int errCode, String errMsg) {
                Toast.makeText(mContext,R.string.circle_posted_fail, Toast.LENGTH_SHORT).show();
            }
        });
    }

    private int uploadCount;

    private void uploadPic(final String title,final String content, List<String> picList) {
        final List<String> urlList = new ArrayList<>();

        uploadCount = picList.size();
        for (int i = 0; i < picList.size(); i++) {

            urlList.add("");
            final int index = i;
            String picUrl = picList.get(i);

            ViseHttp.UPLOAD(CircleApiConstant.UPLOAD_IMG)
                    .baseUrl(ApiConstant.BASE_URL)
                    .addHeader("XX-Token", ServiceFactory.getInstance().getLoginService().getCurrentUser().getToken())
                    .addHeader("XX-Device-Type", "android")
                    .addImageFile("file", FileUtils.getFileByPath(picUrl))
                    .request(new ACallback<BaseTResp<UploadInfo>>() {
                        @Override
                        public void onSuccess(BaseTResp<UploadInfo> data) {
                            hideLoading();
                            if (1 == data.code) {
                                uploadCount--;
                                urlList.remove(index);
                                urlList.add(index, data.data.url);
                                if (uploadCount == 0) {
                                    hideLoading();
                                    send(title,content, urlList);
                                }
                            } else {
                                hideLoading();
                                Toast.makeText(mContext,R.string.circle_img_up_fail, Toast.LENGTH_SHORT).show();
                                //                                ToastUtil.show(data.msg);
                            }
                        }

                        @Override
                        public void onFail(int errCode, String errMsg) {
                            hideLoading();
                            Toast.makeText(mContext,R.string.circle_img_up_error, Toast.LENGTH_SHORT).show();
                        }
                    });
        }
        //        for (int i = 0; i < uploadCount; i++) {
        //            urlList.add("");
        //            final int index = i;
        //            String picUrl = picList.get(i);
        //            try {
        //                String fileName = FileUtils.splitFileName(picUrl);
        //                final AVFile avFile;
        //
        //                avFile = AVFile.withAbsoluteLocalPath(fileName, picUrl);
        //                avFile.saveInBackground(new SaveCallback() {
        //                    @Override
        //                    public void done(AVException e) {
        //                        if (e == null) {
        //                            uploadCount--;
        //                            urlList.remove(index);
        //                            urlList.add(index, avFile.getUrl());
        //                            if (uploadCount == 0) {
        //                                hideLoading();
        //                                send(content, urlList);
        //                            }
        //                        } else {
        //                            hideLoading();
        //                            ToastUtil.show("图片上传失败,请检查网络后重试");
        //                        }
        //                    }
        //                });
        //            } catch (FileNotFoundException e) {
        //                hideLoading();
        //                ToastUtil.show("图片出错...");
        //                e.printStackTrace();
        //            }
        //        }

    }

    @Override
    public void onClickAddNinePhotoItem(BGASortableNinePhotoLayout sortableNinePhotoLayout, View view, int position, ArrayList<String> models) {
        choicePhotoWrapper();
    }

    @Override
    public void onClickDeleteNinePhotoItem(BGASortableNinePhotoLayout sortableNinePhotoLayout, View view, int position, String model, ArrayList<String> models) {
        mPhotoLayout.removeItem(position);
    }

    @Override
    public void onClickNinePhotoItem(BGASortableNinePhotoLayout sortableNinePhotoLayout, View view, int position, String model, ArrayList<String> models) {
        Intent photoPickerPreviewIntent = new MyPhotoPickerPreviewActivity.IntentBuilder(this)
                .previewPhotos(models) // 当前预览的图片路径集合
                .selectedPhotos(models) // 当前已选中的图片路径集合
                .maxChooseCount(mPhotoLayout.getMaxItemCount()) // 图片选择张数的最大值
                .currentPosition(position) // 当前预览图片的索引
                .isFromTakePhoto(true) // 是否是拍完照后跳转过来
                .build();
        startActivityForResult(photoPickerPreviewIntent, RC_PHOTO_PREVIEW);
    }

    @Override
    public void onNinePhotoItemExchanged(BGASortableNinePhotoLayout sortableNinePhotoLayout, int fromPosition, int toPosition, ArrayList<String> models) {
        //排序发生变化
    }

    @AfterPermissionGranted(PRC_PHOTO_PICKER)
    private void choicePhotoWrapper() {
        String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
        if (EasyPermissions.hasPermissions(this, perms)) {
            // 拍照后照片的存放目录，改成你自己拍照后要存放照片的目录。如果不传递该参数的话就没有拍照功能
            File takePhotoDir = new File(Config.PHOTO_PATH);

            Intent photoPickerIntent = new MyPhotoPickerActivity.IntentBuilder(this)
                    .cameraFileDir(takePhotoDir) // 拍照后照片的存放目录，改成你自己拍照后要存放照片的目录。如果不传递该参数的话则不开启图库里的拍照功能
                    .selectedPhotos(mPhotoLayout.getData()) // 当前已选中的图片路径集合
                    .maxChooseCount(mPhotoLayout.getMaxItemCount()) // 图片选择张数的最大值
                    .pauseOnScroll(false) // 滚动列表时是否暂停加载图片
                    .build();
            startActivityForResult(photoPickerIntent, RC_CHOOSE_PHOTO);
        } else {
            EasyPermissions.requestPermissions(this, "图片选择需要以下权限:\n\n1.访问设备上的照片\n\n2.拍照", PRC_PHOTO_PICKER, perms);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        if (requestCode == PRC_PHOTO_PICKER) {
            Toast.makeText(mContext,R.string.circle_requested_permissions, Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == RC_CHOOSE_PHOTO) {
            mPhotoLayout.setData(MyPhotoPickerActivity.getSelectedPhotos(data));
        } else if (requestCode == RC_PHOTO_PREVIEW) {
            mPhotoLayout.setData(MyPhotoPickerPreviewActivity.getSelectedPhotos(data));
        }
    }
}
